<?php
/**
 * author  :  hation
 *  email  : 331596350@qq.com
 * datetime: 2018/1/9 16:39
 */

/*
|--------------------------------------------------------------------------
| 自定义公共函数库Helper
|--------------------------------------------------------------------------
|
*/

use App\Models\Operation;
use Chumper\Zipper\Facades\Zipper;
use Illuminate\Support\Facades\Input;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use App\Common\Response;
use  Illuminate\Support\Facades\Storage;

use Illuminate\Support\Facades\URL;
use App\Models\Progress;
use Illuminate\Http\Request;

/**
 * 对象转数组
 *
 * @param $object object 对象
 *
 * @return mixed 数组
 */
function object_to_array($object)
{
    return json_decode( json_encode( $object ),true );
}

/**
 * 成功返回
 *
 * @param $str
 *
 * @return \Illuminate\Http\RedirectResponse
 */
function success_return($str)
{
    return back()->with( 'success',$str );
}

/**
 * 失败返回
 *
 * @param $str
 *
 * @return \Illuminate\Http\RedirectResponse
 */
function error_return($str)
{
    return back()->with( 'error',$str );
}

/**
 * 统一的数组转json方法
 *
 * @param $arr array|string
 *
 * @return string
 */
function json_return($arr)
{
    return json_encode($arr, JSON_UNESCAPED_UNICODE);
}

/**
 * 对象转数组
 *
 * @param $object object 对象
 *
 * @return mixed 数组
 */
function ota($object)
{
    return collect( $object )->toArray();
}
/**
 * @return string 返回生成的 订单号
 */
function createdNumber()
{
    $yCode   = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    ];
    $nowYear = 2018;
    if ((intval(date('Y')) - $nowYear) > 25) {
        $nowYear = intval(date('Y'));
    }
    $OrderNumber = $yCode[ intval(date('Y')) - $nowYear ]
        . strtoupper(dechex(date('m')))
        . date('d') . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    return $OrderNumber;
}
/**
 * 文件上传
 *
 * @param string $dir 需要上传的目录
 * @param string $k   接收文件Input::file($k)
 *
 * @return int|string 0上传失败 成功上传返回文件名
 */
function upload($dir = 'Uploads/tmp',$k = 'file')
{
    if (!Input::has( $k )){
        return 0;
    }
    $file = Input::file( $k );
    if (!file_exists( $dir )){
        mkdir( $dir,0777,true );
    }
    $filename =createdNumber().'.'.$file->getClientOriginalExtension();
    if (!$file->move( $dir,iconv( "UTF-8","GBK",$filename ) )){
        return 0;
    }
    return $filename;
}


/**
 * 压缩zip文件
 * @param $id int  用户id
 * @param $pid int 产品id
 * @return mixed
 */
function zipDownloads($id,$pid){
    $id=md5($id);
    $pid=md5($pid);
    $files =glob( 'Uploads/resources/'.$id.'/officerFile/'.$pid.'/');
    Zipper::make('Uploads/resources/'.$id.'/officerFile/'.$pid.'/官方文件.zip')->add($files)->close();
    return URL::asset('Uploads/resources/'.$id.'/officerFile/'.$pid.'/官方文件.zip');
}

/**
 * 构造分词语句函数
 *
 * @param $arr array 需要分词查询的数组
 * @param $k   string 需要索引的关键字
 *
 * @return array 返回分词语句
 */
function participleConstruct($arr,$k)
{
    $where = [];
    if (!is_array( $arr ) || !is_string( $k )){
        return [];
    }
    foreach ($arr as $key => $value){
        $where[ $key ][] = $k;
        $where[ $key ][] = "like";
        $where[ $key ][] = '%' . $value . '%';
        $where[ $key ][] = 'or';
    }

    return $where;
}

/**
 * 增加一条操作记录
 *
 * @param $arr
 *
 * @return int 0失败 1 成功
 */
function addOperation($arr)
{
    $item     = [];
    $required = [ 'product_id','operator_id','operator_type','content',"operator_name" ,"process_id","progress_list_id"];
    $other    = [ 'created_at','updated_at' ];
    if (!is_array( $arr ))
        return 0;
    foreach ($required as $v){
        if (!isset( $arr[ $v ] ))
            return 0;
        else
            $item[ $v ] = $arr[ $v ];
    }
    $date = date( "Y-m-d H:i:s" );
    foreach ($other as $v){
        $item[ $v ] = $date;
    }
    $ope = Operation::create( $item );
    if ($ope->save())
        return 1;
    else
        return 0;
}

/**
 * 修改一条操作记录
 *
 * @param $arr
 *
 * @return int 0失败 1 成功
 */
function editOperation($id,$arr)
{
    $required = [ 'product_id','operator_id','operator_type','content' ];
    $other    = [ 'updated_at' ];
    if (!is_array( $arr ))
        return 0;
    $item = Operation::find( $id );
    if (empty( $item )){
        return 0;
    }
    foreach ($required as $v){
        if (!isset( $arr[ $v ] ) || empty( $arr[ $v ] ))
            continue;
        else
            $item[ $v ] = $arr[ $v ];
    }
    $date = date( "Y-m-d H:i:s" );
    foreach ($other as $v){
        $item[ $v ] = $date;
    }
    if ($item->save())
        return 1;
    else
        return 0;
}


/**
 * @param string $title
 * @param int    $num
 *
 * @return array
 */
function get_tags($title = "",$num = 6)
{
    $dict_path  = base_path( 'vendor/scws/pscws4/dict/' );
    $rules_path = base_path( 'vendor/scws/pscws4/etc/' );
    $pscws      = new \SCWS\PSCWS4( 'utf8' );
    $pscws->set_dict( $dict_path . 'dict.utf8.xdb' );
    $pscws->set_rule( $rules_path . 'rules.utf8.ini' );
    $pscws->set_ignore( true );
    $pscws->send_text( $title );
    $words = $pscws->get_tops( $num );
    $pscws->close();
    $tags = [];
    foreach ($words as $val){
        $tags[] = $val[ 'word' ];
    }
    if (empty( $tags )){
        $tags[ 0 ] = $title;
    }

    return $tags;
}


/** 阿里云SMS
 *
 * @param     $data  参数:[ phoneNumber =>电话号码 ]
 * @param int $lenth 验证码长度。
 *
 * @return string    返回结果为json
 */
function sendSMS($data,$SMS_ID,$lenth = 6)
{
    $aliSms    = new Mrgoon\AliSms\AliSms();
    $expiresAt = Carbon::now()->addMinutes( 3 );
    $check     = Cache::has( $data[ 'phoneNumber' ] );
    if (!$check){
        $code = genRandCode( $lenth );
        Cache::store( 'file' )->put( $data[ 'phoneNumber' ],$code,$expiresAt );
    }
    $value    = Cache::store( 'file' )->get( $data[ 'phoneNumber' ] );
    $res      = $aliSms->sendSms( $data[ 'phoneNumber' ],$SMS_ID,[ 'code' => $value ] );
    $response = collect( $res )->toArray();
    if ($response[ 'Code' ] == "OK"){
        $results[ 'identifyingCode' ] = $value;

        return Response::show( 0,"发送成功",$results );
    }
    else{
        $error_msg = config( 'aliyunsms.err_msg_map' )[ $response[ 'Code' ] ];

        return Response::show( 1,$error_msg );
    }


}
/**
 * @param $price float 价格
 * @return string 格式化后的价格
 */
function priceFormat($price)
{
    if($price<1){
        return $price;
    }
    $format = ['','万', '亿','万亿'];
    $m=[0,4,8,12];
    $i      = 0;
    $size   = count($format);
    for ($i ; $i < $size ; $i++) {
        if($price/pow(10, $m[$i])<1){
            break;
        }
    }
    if($i==1||$i==0){
        return $price/pow(10, $m[$i-1]).$format[$i-1];
    }else{
        return  number_format($price/pow(10, $m[$i-1]),1).$format[$i-1];
    }
}

/*
 * 获取随机码
 */

function genRandCode($length)
{
    $str    = null;
    $strPol = "0123456789";
    $max    = strlen( $strPol ) - 1;

    for ($i = 0;$i < $length;$i++){
        $str .= $strPol[ rand( 0,$max ) ];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }

    return $str;
}

/**
 * @param        $file        文件
 * @param        $path_name   路径
 * @param        $fileName    文件名
 *
 * @return array|string       返回值
 */
function uploadFile($file,$path_name,$fileName)
{

    if (!empty( $file )){
        try{
            $file_path    = $path_name;
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext          = $file->getClientOriginalExtension();     // 扩展名
            $realPath     = $file->getRealPath();   //临时文件的绝对路径
            $Filetype     = $file->getClientMimeType();     // image/jpeg
            $stroage      = Storage::disk( 'file' );
            $stroage->makeDirectory( $file_path );
            $saveFileName = $fileName . "." . $ext;
            //  $saveFileName= iconv("UTF-8","GBK",$saveFileName);
            $info = $file->storeAs( $file_path,$saveFileName,"file" );
            if ($info){
                $data = [
                    "name" => $saveFileName,
                    "url"  => $info,
                ];

                return $data;
            }
            else{
                return Response::show( 1,"上传失败" );
            }
        } catch (Exception $exception){
            return Response::show( 1,"未知错误" );
        }

    }
    else{
        return Response::show( 1,"未上传文件" );
    }

}



function download($file, $name)
{
    $fileName = $name ? $name : pathinfo($file, PATHINFO_FILENAME);
    //$filePath = realpath($file);
    $filePath = $file;

    $fp       = fopen($filePath, 'rb');

    if (!$filePath || !$fp) {
        header('HTTP/1.1 404 Not Found');
        echo "Error: 404 Not Found.(server file path error)<!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding --><!-- Padding -->";
        exit();
    }

    $fileName         = $fileName . '.' . pathinfo($filePath, PATHINFO_EXTENSION);

    $encoded_filename = urlencode($fileName);
    $encoded_filename = str_replace("+", "%20", $encoded_filename);

    header('HTTP/1.1 200 OK');
    header("Pragma: public");
    header("Expires: 0");
    header("Content-type: application/octet-stream");
    //header("Content-Length: " . filesize($filePath));
    header("Accept-Ranges: bytes");
    // header("Accept-Length: " . filesize($filePath));

    $ua = $_SERVER["HTTP_USER_AGENT"];

    if (preg_match("/MSIE/", $ua)) {
        header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
    } else
        if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
        }

    ob_end_clean(); // <--有些情况可能需要调用此函数
    // 输出文件内容
    fpassthru($fp);
    exit();
}


/**
 * @param     $salesmanId  业务员id
 * @param     $where       进度表查询条件
 * @param int $cacheTime   缓存时间
 *
 * @return array           返回数据
 */
function getTaskNumber($salesmanId,$where,$cacheTime=3){
    $expiresAt = Carbon::now()->addMinutes($cacheTime);
    $cache_name="task_number_".$salesmanId;
    $check     = Cache::has($cache_name);
    if(!$check){
        $processNum=[
            "total"=>0,
            "processing"=>0,
            "not_begin"=>0,
            "completed"=>0,
        ];
        $with_process = [
            "ProgressList",
        ];
        $processModel=Progress::with($with_process)->where($where)->get();
        if(!empty($processModel)){
            $process=$processModel->toArray();
            $processNum['total']=count($process);
            foreach ($process as $key => $value){
                if(empty($value['progress_list'])){
                    ++$processNum['not_begin'];
                }elseif ($value['progress_list']['progress_state']==0){
                    ++$processNum['processing'];
                }elseif (in_array($value['progress_list']['progress_state'],[1,2,3])){
                    ++$processNum['completed'];
                }
            }
            Cache::store( 'file' )->put($cache_name,$processNum,$expiresAt );
        }
    }else{
        $processNum=Cache::store( 'file' )->get($cache_name);
    }
    return $processNum;
}



/**
 * 校验是否是合法的非负浮点数
 * @param $num string 需要检验的串
 * @return int 1 yes 0 no
 */
function checkNum($num){
    return preg_match("/^\d+(\.\d+)?$/",$num);
}



